package com.smart.manager.weixin.mp.cfg;


import com.smart.manager.weixin.mp.entities.enums.WeixinMpAccountType;
import com.smart.manager.weixin.mp.entities.models.WeixinMpAccount;
import com.smart.manager.weixin.mp.entities.models.query.QWeixinMpAccount;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Log4j2
public class WxmpCmdRunner implements CommandLineRunner {

    private final WxMpService wxMpService;


    @Override
    public void run(String... args) {
        log.warn("初始化微信公众号配置......");
        new QWeixinMpAccount().type.eq(WeixinMpAccountType.SERVICE_ACCOUNT_AUDITED)
                .findEach(this::addConfig);

    }

    public void addConfig(WeixinMpAccount account) {
        WxMpDefaultConfigImpl mpConfig = new WxMpDefaultConfigImpl();
        mpConfig.setAppId(account.getAppId());
        mpConfig.setSecret(account.getSecret());
        mpConfig.setToken(account.getToken());
        mpConfig.setAesKey(account.getAesKey());
        wxMpService.addConfigStorage(account.getAppId(), mpConfig);

    }

    public void removeConfig(String appId) {
        wxMpService.removeConfigStorage(appId);
    }
}
